﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Baosight.ZNH.ZMCommon;
using Baosight.ZNH.ZMCommon.ChildWindows;
using Baosight.Platform.Core;
using Baosight.Platform.Core.UI.Controls;
using Telerik.Windows.Controls;
using Baosight.Platform.Core.ServiceModel;
using Baosight.ZNH.ZMCommon.Prompt;

namespace Baosight.ZNH.ZMCT.UI.PopWindows
{
    public partial class ModelAdd : EFViewCmes
    {
        public ModelAdd(string dialogType)
        {
            InitializeComponent();
            base.BeforeAction += OnBeforeAction;
            Init(dialogType);
        }

        /// <summary>
        /// 初始化父类EFViewCmesProperty的值，每次点击“确定”、“返回”时执行此方法，从新赋值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBeforeAction(object sender, EventArgs e)
        {
            EFViewCmesProperty _view = new EFViewCmesProperty();
            _view.DataFields = this.spWindows.GetChildObjects<EFDataField>(null, true);
            base.ViewProperty = _view;
        }

        /// <summary>
        /// 初始化页面数据
        /// </summary>
        private void Init(string type)
        {
            type = type == null ? "insert" : type.ToLower();

            switch (type)
            {
                case "insert":

                    base.Mode = OperationMode.Insert;
                    break;
                case "update":
                    base.Mode = OperationMode.Update;
                    break;
                case "detail":
                    this.Commit.Visibility = Visibility.Collapsed;
                    BaseTools.EFDataFieldNotEnabled(this.spWindows.GetChildObjects<EFDataField>(null, true));
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 确定按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CommitClick(object sender, RoutedEventArgs e)
        {
            base.OnCommitButtonClick("ZMCT20", sender, e);
        }

        /// <summary>
        /// 取消按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancelClick(object sender, RoutedEventArgs e)
        {
            CmesWindows _window = this.Parent as CmesWindows;
            _window.DialogResult = false;
            _window.Close();
        }

        private void NextClick(object sender, RoutedEventArgs e)
        {
            if (ValidateResultField())
            {
                if (validateSql())
                {
                    EIInfo info = new EIInfo();
                    info.Set("service", "ZMCT20");
                    info.Set("method", "validateSql");
                    info.Set("fdDsId", this.fdDs.Value);
                    info.Set("fdSql", this.fdSql.Value);
                    info.Set("fdSmsType", this.fdSmsType.Value);

                    HttpServiceAgent agent = new HttpServiceAgent();
                    agent.CallService(info, ValidateSqlCompleted);
                }
            }
        }


        private void ValidateSqlCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.GetStatus() == -1)
            {
                ValidateMessagePopup(e.EIInfo.GetMsg());
            }
            else
            {
                this.fdModelName.Visibility = Visibility.Collapsed;
                this.fdSmsType.Visibility = Visibility.Collapsed;
                this.fdDs.Visibility = Visibility.Collapsed;
                this.fdSql.Visibility = Visibility.Collapsed;
                this.fdLabel.Visibility = Visibility.Collapsed; 
                this.fdLabel1.Visibility = Visibility.Collapsed;
                this.Show.Visibility = Visibility.Collapsed;

                this.fdModelContent.Visibility = Visibility.Visible;
                
                this.Next.Visibility = Visibility.Collapsed;
                this.Last.Visibility = Visibility.Visible;
                this.Insert.Visibility = Visibility.Visible;
                this.Commit.Visibility = Visibility.Visible;
            }
        }

        /// <summary>
        /// EFDatafield容器的全局合法性校验
        /// </summary>
        /// <param name="element">EFDatafield的容器控件</param>
        /// <returns>是否全部合法</returns>
        public bool ValidateResultField()
        {
            bool result = true;

            List<EFDataField> dataFields = this.GetChildObjects<EFDataField>(null);
            foreach (EFDataField field in dataFields)
            {
                if (field.eBindingName.Contains("result-0"))
                {
                    if (field.Visibility == Visibility.Visible)
                    {
                        result = field.Validate() && result;
                    }
                }
            }
            return result;
        }

        private bool validateSql()
        {
            if (this.fdSmsType.Value.Equals("即时消息"))
            {
                if (!this.fdSql.Value.ToString().ToLower().Contains("keyid"))
                {
                    ValidateMessagePopup("消息类型为即时消息时，sql中必须包含为'keyid'的别名字段！");
                    return false;
                }

                if (!this.fdSql.Value.ToString().ToLower().Contains("mobilenum"))
                {
                    ValidateMessagePopup("消息类型为即时消息时，sql中必须包含为'mobilenum'的别名字段！");
                    return false;
                }

                if (!this.fdSql.Value.ToString().ToLower().Contains(":currentdate")
                        || (this.fdSql.Value.ToString().ToLower().LastIndexOf("where") != -1
                            && (this.fdSql.Value.ToString().ToLower().LastIndexOf("where")
                                > this.fdSql.Value.ToString().ToLower().LastIndexOf(":currentdate"))))
                {
                    ValidateMessagePopup("消息类型为即时消息时，sql中必须包含为':currentdate'的查询条件！");
                    return false;
                }
            }

            if (this.fdSql.Value.ToString().ToLower().StartsWith("select * "))
            {
                ValidateMessagePopup("不能已select * 开头！");
                return false;
            }

            return true;
        }

        private void LastClick(object sender, RoutedEventArgs e)
        {
            this.fdModelName.Visibility = Visibility.Visible;
            this.fdSmsType.Visibility = Visibility.Visible;
            this.fdDs.Visibility = Visibility.Visible;
            this.fdSql.Visibility = Visibility.Visible;
            this.fdLabel.Visibility = Visibility.Visible;
            this.fdLabel1.Visibility = Visibility.Visible;
            this.Show.Visibility = Visibility.Visible;
            this.fdModelContent.Visibility = Visibility.Collapsed;
            
            this.Next.Visibility = Visibility.Visible;
            this.Last.Visibility = Visibility.Collapsed;
            this.Insert.Visibility = Visibility.Collapsed;
            this.Commit.Visibility = Visibility.Collapsed;
        }

        private void InsertClick(object sender, RoutedEventArgs e)
        {
            EIInfo info = new EIInfo();
            info.Set("service", "ZMCT20");
            info.Set("method", "decomposeColumns");
            info.Set("fdSql", this.fdSql.Value);
            info.Set("fdSmsType", this.fdSmsType.Value);

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(info, DecomposeColumnsCompleted);
        }

        private void DecomposeColumnsCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            OpenFieldPopup(e.EIInfo, "插入", "insert", null);
        }

        private void ShowClick(object sender, RoutedEventArgs e)
        {
            if (validateSql())
            {
                EIInfo info = new EIInfo();
                info.Set("service", "ZMCT09");
                info.Set("method", "showQuery");
                info.Set("fdSql", this.fdSql.Value);
                info.Set("fdDs", this.fdDs.Value);

                HttpServiceAgent agent = new HttpServiceAgent();
                agent.CallService(info, ShowCompleted);
            }
        }

        private void ShowCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            EIInfo info = e.EIInfo;
            if(info.GetStatus() != -1)
            {
                ShowQueryValues showQueryValues = new ShowQueryValues();//构造一个新的页面
                showQueryValues.EIDataContext = new Platform.Core.UI.EIDataContext();
                showQueryValues.EIDataContext.Update(info);

                CmesWindows _popup = new CmesWindows();//构造一个弹出页面
                _popup.WindowStartupLocation = Telerik.Windows.Controls.WindowStartupLocation.CenterOwner;
                _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
                _popup.Header = "查看";//设置Title
                _popup.Content = showQueryValues;//让新增页面在弹出窗口显示
                _popup.Closed += new EventHandler<WindowClosedEventArgs>(CmesWindow_Closed);

                _popup.ShowDialog();//模态显示弹出窗口
            }
            else
            {
                ValidateMessagePopup(info.GetMsg());
            }
        }

        /// <summary>
        /// 构造模板页面内容、弹出页面
        /// </summary>
        /// <param name="eIInfo"></param>
        /// <param name="title"></param>
        private void OpenFieldPopup(EIInfo _eIInfo, string _title, string _dialogType, string _args)
        {
            SelectField selectField = new SelectField(this.fdModelContent);//构造一个新的页面
            selectField.EIDataContext = new Platform.Core.UI.EIDataContext();
            selectField.EIDataContext.Update(_eIInfo);

            CmesWindows _popup = new CmesWindows();//构造一个弹出页面
            _popup.WindowStartupLocation = Telerik.Windows.Controls.WindowStartupLocation.CenterOwner;
            _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
            _popup.Header = _title == null ? "" : _title;//设置Title
            _popup.Content = selectField;//让新增页面在弹出窗口显示
            _popup.Closed += new EventHandler<WindowClosedEventArgs>(CmesWindow_Closed);

            _popup.ShowDialog();//模态显示弹出窗口
        }

        /// <summary>
        /// 弹出窗口关闭时执行的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmesWindow_Closed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == true)
            {
                
            }

            //按钮生效
            base.TempButtonOpen(true);

            //超链接生效
            if (base.TempHyperlink != null)
            {
                base.TempHyperlink.IsEnabled = true;
                base.TempHyperlink = null;
            }
        }

        /// <summary>
        /// 提示错误消息
        /// </summary>
        /// <param name="str"></param>
        private void ValidateMessagePopup(string str)
        {
            Prompts pop = Prompts.getInstance();
            pop.SetMsg(str);
            pop.Show(6);

            return;
        }
    }
}
